<template>
    <van-nav-bar title="菜谱详情页" left-text="返回" left-arrow @click-left="back">
    </van-nav-bar>

    <div class="content" v-if="!loading && !errorState">
        <h2 class="title">{{ title }}</h2>
        <div class="brief" v-html="brief" />
        <div class="detail">
            <van-tabs v-model:active="active">
                <!-- 原料和工具 -->
                <van-tab title="原料和工具">
                    <div v-html="material" />
                </van-tab>
                <!-- 计算 -->
                <van-tab title="计算">
                    <div v-html="cal" />
                </van-tab>
                <van-tab title="操作">
                    <div v-html="steps"></div>
                </van-tab>

                <!-- 附加内容 -->
                <van-tab title="附加内容">
                    <div v-html="extra"></div>
                </van-tab>
            </van-tabs>
        </div>
        <VerticalSpace size="55px" />
    </div>

    <!-- 加入菜篮 -->
    <div class="btn-group" v-if="!loading">
        <div class="star-container" @click="collect">
            <van-icon name="star-o" class="star-btn" size="18" v-show="!collectState" />
            <van-icon name="star" color="rgb(243, 35, 41)" class="star-btn" size="18" v-show="collectState" />
            <span>收藏</span>
        </div>
        <div class="basket-container" @click="goBasket">
            <van-icon name="cart-o" class="star-btn" :badge="basketBadge" size="18" />
            <span>菜篮</span>
        </div>
        <van-button round type="success" class="join-btn" color="linear-gradient(to right, #ff6034, #ee0a24)"
            @click="join">加入菜篮</van-button>
    </div>

    <!-- 显示空状态 -->
    <van-empty image="error" description="菜谱未找到" v-if="!loading && errorState" />

</template>

<script setup lang="ts">
import req from '@/utils/requests'
import { marked } from 'marked'
import { assert } from '@/utils/assert'
import VerticalSpace from '@/components/VerticalSpace.vue'
import { useBasketStore, type Cook } from '@/stores/basket.ts'

// 路由实例
const router = useRouter()
const route = useRoute()

// 标签页激活状态
const active = ref(0)
// 是否正在加载
const loading = ref(true)
// 菜谱异常
const errorState = ref(false)

// 收藏
const collectState = ref(false)

// 菜谱渲染
const title = ref('')
// 简介
const brief = ref('')
// 材料
const material = ref('')
// 计算
const cal = ref('')
// 操作步骤
const steps = ref()
// 附加内容
const extra = ref('')


let cook: Cook

// 菜篮
const basketStore = useBasketStore()

// 菜篮的徽标
const basketBadge = computed(() => {
    return basketStore.size()
})

const back = () => {
    console.log("返回上一页")
    router.back()
}



onMounted(async () => {
    try {
        // 获取组件传递过来的参数
        const param = route.params
        const cookId = param.cookId
        console.log(`cookId: ${cookId}`)
        cook = await req.get(`/api/cook/${cookId}`)
        renderContent(cook.content)
    } catch (error) {
        console.warn('获取菜谱详情异常: ', error)
        errorState.value = true
    } finally {
        loading.value = false
    }
})

interface Section {
    title: string;
    content: string;
}

// 渲染
const renderContent = async (str: string): Promise<void> => {
    const content: Array<Section> = extractRecipeParts(str)
    assert(content.length == 6, "菜谱解析出了问题")
    // 标题和简介
    title.value = content[0].content
    brief.value = await directRender(content[1].content)
    // 原料和工具
    material.value = await directRender(content[2].content)
    // 修改cook的content属性, 便于加入购物车
    cook.content = content[2].content
    // 计算
    cal.value = await directRender(content[3].content)
    steps.value = await directRender(content[4].content)
    // 附加内容
    extra.value = await directRender(content[5].content)
}

const extractRecipeParts = (text: string): Array<Section> => {
    const parts = text.split(/\n## /);

    // 处理标题和介绍部分
    const titleAndIntro = parts[0].split('\n');
    const title = titleAndIntro[0].replace('# ', '');
    const intro = titleAndIntro.slice(2, -1).join('\n').trim();

    // 处理其他部分
    const recipeParts = parts.slice(1).map(part => {
        const [sectionTitle, ...content] = part.split('\n');
        return {
            title: sectionTitle.trim(),
            content: content.join('\n').trim()
        };
    });

    return [
        { title: '标题', content: title },
        { title: '介绍', content: intro },
        ...recipeParts
    ];
};


// 直接渲染markdown
const directRender = async (str: string): Promise<string> => marked.parse(str)


const collect = () => {
    const params = route.params
    console.log(`收藏: ${params.cookId}`)
    collectState.value = !collectState.value
}

// 去菜篮
const goBasket = () => {
    router.push('/basket')
}

// 加入菜篮
const join = () => {
    console.log('加入菜篮')
    basketStore.add(cook)
}

</script>

<style scoped>
.content {
    background-color: var(--color-background-soft);

    .title {
        padding-top: 10px;
        padding-left: var(--van-padding-md);
        font-weight: bold;
    }

    .brief {
        padding-left: var(--van-padding-md);
        padding-right: var(--van-padding-md);
        margin-top: 10px;
        font-size: small;
    }

    :deep(img) {
        max-width: 100%;
        height: auto;
    }

    .detail {
        margin-left: var(--van-padding-md);
        margin-right: var(--van-padding-md);
        margin-top: var(--van-padding-md);
        background-color: white;
        border-radius: 10px;

        /* :deep()能够让样式对scope之外的元素生效 */
        :deep(.van-tabs__content) {
            padding-left: var(--van-padding-md);
            padding-right: var(--van-padding-md);
            padding-top: 10px;
        }

        :deep(ul) {
            list-style-type: circle;
        }

        :deep(li) {
            padding-bottom: 10px;
            padding-right: 10px;
            margin-left: 10px;
        }

        .step-btn {
            margin-left: 5px;
            margin-top: 5px;
        }

        :deep(.van-step--vertical:not(:last-child):after) {
            /* 去掉边框 */
            border-bottom-width: 0px;
        }

    }
}

.btn-group {
    position: fixed;
    bottom: 0;
    height: var(--van-tabbar-height);
    width: 100%;
    background: var(--van-tabbar-background);
    z-index: var(--van-tabbar-z-index);
    box-sizing: content-box;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .star-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        font-size: 12px;
    }

    .join-btn {
        flex: 3;
        margin-right: 10px;
        height: 30px;
    }

}

.basket-container {
    display: flex;
    flex-direction: column;
    flex: 1;
    font-size: 12px;
    justify-content: center;
    align-items: center;
}

.btn-group:after {
    border-width: var(--van-border-width) 0;
    content: " ";
    position: absolute;
    box-sizing: border-box;
    pointer-events: none;
    border: 0 solid var(--van-border-color);
    top: -50%;
    right: -50%;
    bottom: -50%;
    left: -50%;
    transform: scale(.5);
}
</style>